﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Kiel.Pdf
{
    /// <summary>
    /// Represents a PDF document.
    /// </summary>
    public class Document
    {
        private readonly CrossReferenceTable xref = new CrossReferenceTable();

        /// <summary>
        /// Initializes a new PDF document.
        /// </summary>
        public Document()
        {
            this.Pages = new Pages();
            this.Version = PdfVersion.PDF_1_7;
        }

        /// <summary>
        /// Gets the pages of this document.
        /// </summary>
        public Pages Pages { get; private set; }

        /// <summary>
        /// Gets or sets the PDF version specification of this document.
        /// </summary>
        public PdfVersion Version { get; set; }

        /// <summary>
        /// Writes this <see cref="Document"/> into the given stream.
        /// </summary>
        /// <param name="stream"></param>
        public void Write(Stream stream)
        {
            StreamWriter writer = new StreamWriter(stream);
            this.WriteHeader(writer);
            this.WriteBody(writer);
        }

        private void WriteBody(StreamWriter writer)
        {
            this.xref.Clear();
        }

        private void WriteHeader(StreamWriter writer)
        {
            // write the pdf version...
            writer.WriteLine(new Comment(this.Version.ToDisplayString()));
            // write a comment line with 4 binary characters for file transfer applications...
            writer.WriteLine(new Comment(Encoding.UTF8.GetString(new byte[] { 0xe2, 0xe3, 0xcf, 0xc3 })));
        }
    }
}
